<!--
  门卫管理组件
  创建时间：2025-09-12
  作者：开发团队
  目的：管理系统中的门卫账号
-->

<template>
  <div class="guard-management">
    <el-card class="management-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h2>门卫管理</h2>
          <div class="header-actions">
            <el-button
              type="primary"
              :loading="loading"
              @click="showAddDialog"
            >
              <el-icon><Plus /></el-icon>
              添加门卫账号
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 门卫列表 -->
      <div class="guards-section">
        <el-table
          v-loading="loading"
          :data="guards"
          stripe
          class="guards-table"
        >
          <el-table-column prop="username" label="用户名" width="120" />
          
          <el-table-column prop="name" label="姓名" width="120" />
          
          <el-table-column prop="phone" label="手机号" width="140">
            <template #default="{ row }">
              {{ row.phone || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getGuardStatusType(row.status)">
                {{ getGuardStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="last_login" label="最后登录" width="180">
            <template #default="{ row }">
              {{ row.last_login ? formatDate(row.last_login) : '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                text
                size="small"
                @click="showEditDialog(row)"
              >
                编辑
              </el-button>
              <el-button
                type="warning"
                text
                size="small"
                @click="showResetPasswordDialog(row.id)"
              >
                重置密码
              </el-button>
              <el-button
                type="danger"
                text
                size="small"
                @click="deleteGuard(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          
          <template #empty>
            <el-empty description="暂无门卫数据" />
          </template>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalGuards"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 添加/编辑门卫对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="guardFormRef"
        :model="guardForm"
        :rules="guardRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="guardForm.username" :disabled="isEditing" />
        </el-form-item>
        
        <el-form-item v-if="!isEditing" label="密码" prop="password">
          <el-input
            v-model="guardForm.password"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item v-if="!isEditing" label="确认密码" prop="confirmPassword">
          <el-input
            v-model="guardForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="guardForm.name" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="guardForm.phone" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="guardForm.status" placeholder="请选择状态">
            <el-option label="活跃" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitGuard"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPasswordDialogVisible"
      title="重置密码"
      width="400px"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="80px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPasswordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitResetPassword"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { showError, showSuccess } from '@/utils/message'
import { formatDate } from '@/utils/date'
import type { FormInstance, FormRules } from 'element-plus'
import type { Guard, GuardForm } from '@/types/admin'
import { adminApi } from '@/api/admin'

// 响应式状态
const loading = ref(false)
const submitting = ref(false)
const guards = ref<Guard[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalGuards = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditing = ref(false)
const editingGuardId = ref<number | null>(null)
const resetPasswordDialogVisible = ref(false)
const resettingGuardId = ref<number | null>(null)

// 表单引用
const guardFormRef = ref<FormInstance>()
const resetPasswordFormRef = ref<FormInstance>()

// 表单数据
const guardForm = ref<GuardForm>({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  phone: '',
  status: 'active'
})

const resetPasswordForm = ref({
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const guardRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度为6-50个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: unknown, value: string, callback: (error?: Error) => void) => {
        if (value !== guardForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 100, message: '姓名长度为1-100个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const resetPasswordRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度为6-50个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: unknown, value: string, callback: (error?: Error) => void) => {
        if (value !== resetPasswordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

/**
 * 加载门卫列表
 */
const loadGuards = async (): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API获取门卫列表
    const response = await adminApi.getGuards({
      page: currentPage.value,
      size: pageSize.value
    })
    
    // 正确处理分页数据
    guards.value = response.items
    totalGuards.value = response.total
  } catch (error) {
    console.error('加载门卫列表失败:', error)
    showError('加载门卫列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 显示添加对话框
 */
const showAddDialog = (): void => {
  dialogTitle.value = '添加门卫账号'
  isEditing.value = false
  editingGuardId.value = null
  guardForm.value = {
    username: '',
    password: '',
    confirmPassword: '',
    name: '',
    phone: '',
    status: 'active'
  }
  dialogVisible.value = true
}

/**
 * 显示编辑对话框
 * :param guard: 门卫数据
 */
const showEditDialog = (guard: Guard): void => {
  dialogTitle.value = '编辑门卫账号'
  isEditing.value = true
  editingGuardId.value = guard.id
  guardForm.value = {
    username: guard.username,
    password: '',
    confirmPassword: '',
    name: guard.name,
    phone: guard.phone || '',
    status: guard.status
  }
  dialogVisible.value = true
}

/**
 * 提交门卫表单
 */
const submitGuard = async (): Promise<void> => {
  if (!guardFormRef.value) return
  
  try {
    // 表单验证
    await guardFormRef.value.validate()
    
    submitting.value = true
    
    if (isEditing.value && editingGuardId.value) {
      // 调用API更新门卫
      await adminApi.updateGuard(editingGuardId.value, {
        name: guardForm.value.name,
        phone: guardForm.value.phone || '',
        // 注意：status字段不在GuardRequest类型中，需要后端API支持
        username: guardForm.value.username,
        campus_id: 1 // 默认院区ID，实际应用中应从选择器中获取
      })
      showSuccess('门卫信息更新成功')
    } else {
      // 调用API创建门卫
      await adminApi.createGuard({
        username: guardForm.value.username,
        password: guardForm.value.password,
        name: guardForm.value.name,
        phone: guardForm.value.phone || '',
        // 注意：status字段不在GuardRequest类型中，需要后端API支持
        campus_id: 1 // 默认院区ID，实际应用中应从选择器中获取
      })
      showSuccess('门卫账号添加成功')
    }
    
    dialogVisible.value = false
    await loadGuards()
  } catch (error) {
    console.error('提交门卫信息失败:', error)
    showError('提交门卫信息失败')
  } finally {
    submitting.value = false
  }
}

/**
 * 显示重置密码对话框
 * :param guardId: 门卫ID
 */
const showResetPasswordDialog = (guardId: number): void => {
  resettingGuardId.value = guardId
  resetPasswordForm.value = {
    newPassword: '',
    confirmPassword: ''
  }
  resetPasswordDialogVisible.value = true
}

/**
 * 提交重置密码表单
 */
const submitResetPassword = async (): Promise<void> => {
  if (!resetPasswordFormRef.value || !resettingGuardId.value) return
  
  try {
    // 表单验证
    await resetPasswordFormRef.value.validate()
    
    submitting.value = true
    
    // 调用API重置密码
    await adminApi.changeGuardPassword(resettingGuardId.value, resetPasswordForm.value.newPassword)
    showSuccess('密码重置成功')
    
    resetPasswordDialogVisible.value = false
  } catch (error) {
    console.error('重置密码失败:', error)
    showError('重置密码失败')
  } finally {
    submitting.value = false
  }
}

/**
 * 删除门卫
 * :param guardId: 门卫ID
 */
const deleteGuard = async (guardId: number): Promise<void> => {
  try {
    // 调用API删除门卫
    await adminApi.deleteGuard(guardId)
    showSuccess(`门卫删除成功`)
    await loadGuards()
  } catch (error) {
    console.error('删除门卫失败:', error)
    showError('删除门卫失败')
  }
}

/**
 * 获取门卫状态标签类型
 * :param status: 门卫状态
 * :return: Element Plus标签类型
 */
const getGuardStatusType = (status: string): 'success' | 'danger' | 'info' => {
  switch (status) {
    case 'active':
      return 'success'
    case 'disabled':
      return 'danger'
    default:
      return 'info'
  }
}

/**
 * 获取门卫状态文本
 * :param status: 门卫状态
 * :return: 状态文本
 */
const getGuardStatusText = (status: string): string => {
  switch (status) {
    case 'active':
      return '活跃'
    case 'disabled':
      return '禁用'
    default:
      return status
  }
}

/**
 * 处理分页大小变化
 * :param val: 新的分页大小
 */
const handleSizeChange = (val: number): void => {
  pageSize.value = val
  currentPage.value = 1
  loadGuards()
}

/**
 * 处理当前页变化
 * :param val: 新的当前页码
 */
const handleCurrentChange = (val: number): void => {
  currentPage.value = val
  loadGuards()
}

/**
 * 组件挂载时初始化数据
 */
onMounted(() => {
  loadGuards()
})
</script>

<style scoped>
.guard-management {
  height: 100%;
}

.management-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.guards-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.guards-table {
  flex: 1;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>